"""断言封装"""
import allure
import jsonpath
import logging
import pytest

from config.config import RESPONSE_TIME_LIMIT
from utils.excel_utils import slowApiCsv
from utils.exception_utils import AssertException
from utils.jsonpath_utils import jsonpath_exp
from utils.logger_utils import *
from utils.mysql_utils import MysqlUtils
from utils.request_utils import send_sql


def assert_json(param,r):
    try:
        if param["check"]:
            with allure.step("json断言"):
                for c,e in zip(eval(param["check"]),eval(param["expect"])):
                    json_assert = jsonpath_exp(r.json(),c)
                    info(f"json断言比较：当前结果（{json_assert}）==预期结果（{e}）")
                    pytest.assume(json_assert == e)
    except Exception as e:
        info(f"断言异常！{e}")
        raise  AssertException

def assert_sql(param):
    try:
         if param["sql_check"]:
            with allure.step("sql断言"):
                dict_sql = MysqlUtils().send_sql_one(param["sql_check"])
                for v in dict_sql.values():
                    pytest.assume(param["sql_expect"] == v)
    except Exception as e:
        info(f"断言异常！{e}")
        raise  AssertException

def assert_status(param,r):
    try:
        if param["status_check"]:
            with allure.step("状态码断言"):
                pytest.assume(r.status_code == param["status_check"])
                info(f"状态码断言比较：当前结果（{r.status_code}）==预期结果（{param['status_check']}）")
    except Exception as e:
        info(f"断言异常！{e}")
        raise  AssertException

def assert_response_time(param,r):
    try:
        res_time = r.elapsed.total_seconds()
        info(f"当前响应时间为：{res_time}秒，要求时间0.5s")

        if res_time > RESPONSE_TIME_LIMIT:
            slowApiCsv(param,r,"../logs/slowApi.csv")

        pytest.assume(res_time < RESPONSE_TIME_LIMIT)
    except Exception as e:
        info(f"断言异常！{e}")
        raise  AssertException

